package com.dongdongshop.controller;

import com.dongdongshop.data.Result;
import com.dongdongshop.data.ResultEnum;
import com.dongdongshop.pojo.TbUser;
import com.dongdongshop.service.LoginService;
import com.dongdongshop.service.UserService;
import com.dongdongshop.util.ShiroUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

@Controller
@RequestMapping("user")
public class UserController {

    @DubboReference
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("register")
    @ResponseBody
    public Result register(TbUser tbUser,String code){
        try{
            String salt = ShiroUtils.generateSalt(6);
            tbUser.setSalt(salt);
            tbUser.setPassword(ShiroUtils.encryptPassword("MD5", tbUser.getPassword(), salt, 10));
            tbUser.setCreated(new Date());
            tbUser.setUpdated(new Date());
            tbUser.setSourceType("1");
            tbUser.setStatus("Y");
            String vcode =(String) redisTemplate.boundValueOps(tbUser.getPhone()).get();
            if(!code.equals(vcode)){
                return Result.respones(ResultEnum.CODEERROR);
            }
            userService.insertRegister(tbUser);
            return Result.ok();
        }catch (Exception e){
            e.printStackTrace();
            return Result.respones(ResultEnum.ERROR);
        }
    }

    @RequestMapping("toLogin")
    public String toLogin(){

        return "login";
    }

    @RequestMapping("getLogin")
    @ResponseBody
    public Result getLogin(TbUser tbUser){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(tbUser.getUsername(), tbUser.getPassword());
        try {
            subject.login(token);
            return Result.respones(ResultEnum.SUCCESS);
        }catch (UnknownAccountException ue) {
            return Result.respones(ResultEnum.PASSWORDERROR);
        }catch (IncorrectCredentialsException ie) {
            return Result.respones(ResultEnum.USERNAMEERROR);
        }
    }

}
